package mwt.xml.xdbforms.schemalayer.types;

import java.sql.Blob;
import javax.xml.XMLConstants;
import mwt.xml.xdbforms.dblayer.metadata.impl.ColumnMetaData;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;

/**
 * Definisce il tipo
 * BLOB, MEDIUMBLOB, LONGBLOB
 * @author Gianfranco Murador
 */
public class XmlBlob extends XmlTypes {

    public XmlBlob() {
    }

    public XmlBlob(Document doc) {
        super(doc);
    }

    private void buildFragment(ColumnMetaData metaData) {

        Element xtype, restriction, maxLength;
        fragment = doc.createDocumentFragment();

        xtype = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:simpleType");
        xtype.setAttribute("name", typeName);
        metaData.setXschemaTypeName(typeName);

        restriction = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:restriction");
        restriction.setAttribute("base", "xs:base64Binary");

        maxLength = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:maxLength");

        Integer length = metaData.getDisplaySize();
        maxLength.setAttribute("value", length.toString());

        xtype.appendChild(restriction);
        restriction.appendChild(maxLength);
        fragment.appendChild(xtype);

    }

    @Override
    public DocumentFragment getSchemaType(ColumnMetaData cmd) {
        typeName = cmd.getTypeName();

        if (typeName.equals("BLOB") || typeName.equals("MEDIUMBLOB") || typeName.equals("LONGBLOB")) {
            buildFragment(cmd);
            return fragment;
        } else {
            return nextType.getSchemaType(cmd);
        }

    }

    @Override
    public Object getXSchemaToJavaType(String baseType, String value) {

        if (baseType.startsWith("BLOB") || baseType.startsWith("MEDIUMBLOB") || baseType.startsWith("LONGBLOB")) {

            byte[]  b = value.getBytes();            
            return b;
        } else {

            return nextType.getXSchemaToJavaType(baseType, value);

        }
    }
}

